package com.zone.canvas;

import android.Manifest;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.zone.canvas.base.BaseActivity;
import com.zone.canvas.tools.EditingToolsAdapter;
import com.zone.canvas.tools.ToolType;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import com.zone.editor.SaveSettings;
import com.zone.editor.inter.Editor;
import com.zone.editor.inter.OnEditorListener;
import com.zone.editor.pixel.PixelEditorView;
import com.zone.editor.shape.ShapeBuilder;
import com.zone.editor.shape.ShapeType;
import com.zone.editor.TextStyleBuilder;
import com.zone.editor.ViewType;
import com.zone.editor.zoom.ZoomLayout;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.zone.canvas.FileSaveHelper.isSdkHigherThan28;

public class EditPixelTailActivity extends BaseActivity implements OnEditorListener,
        View.OnClickListener,
        PropertiesBSFragment.Properties,
        ShapeBSFragment.Properties,
        EmojiBSFragment.EmojiListener,
        StickerBSFragment.StickerListener, EditingToolsAdapter.OnItemSelected
{

    private static final String TAG = EditPixelTailActivity.class.getSimpleName();

    private Editor editor;
    private PixelEditorView pixelEditorView;
    private PropertiesBSFragment mPropertiesBSFragment;
    private ShapeBSFragment mShapeBSFragment;
    private ShapeBuilder mShapeBuilder;
    private EmojiBSFragment mEmojiBSFragment;
    private StickerBSFragment mStickerBSFragment;
    private TextView mTxtCurrentTool;
    private RecyclerView mRvTools;
    private final EditingToolsAdapter mEditingToolsAdapter = new EditingToolsAdapter(this);

    private FileSaveHelper mSaveFileHelper;
    private ZoomLayout zoomLayout;
    private AppCompatButton btnStartScroll;
    private AppCompatButton btnEndScroll;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        makeFullScreen();
        setContentView(R.layout.activity_edit_pixel_tail);

        initViews();

        mPropertiesBSFragment = new PropertiesBSFragment();
        mEmojiBSFragment = new EmojiBSFragment();
        mStickerBSFragment = new StickerBSFragment();
        mShapeBSFragment = new ShapeBSFragment();
        mStickerBSFragment.setStickerListener(this);
        mEmojiBSFragment.setEmojiListener(this);
        mPropertiesBSFragment.setPropertiesChangeListener(this);
        mShapeBSFragment.setPropertiesChangeListener(this);

        LinearLayoutManager llmTools = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRvTools.setLayoutManager(llmTools);
        mRvTools.setAdapter(mEditingToolsAdapter);
        //设置固定区域画笔颜色
//        RectF rectF = new RectF(0f,0f,500f,500f);
//        pixelEditorView.setStaticRect(rectF, R.color.blue);

        editor = new Editor.Builder(this, pixelEditorView).build(); // build editor sdk

        editor.setOnEditorListener(this);

        mSaveFileHelper = new FileSaveHelper(this);

        pixelEditorView.getSource().setImageResource(R.drawable.isd_tail_bg_grey);
    }

    private void initViews() {
        ImageView imgUndo;
        ImageView imgRedo;
        ImageView imgSave;
        ImageView imgClose;
        pixelEditorView = findViewById(R.id.pixelEditorView);
        mTxtCurrentTool = findViewById(R.id.txtCurrentTool);
        mRvTools = findViewById(R.id.rvConstraintTools);
        zoomLayout = findViewById(R.id.zoom);
        btnStartScroll = findViewById(R.id.btnStartScroll);
        btnStartScroll.setOnClickListener(this);
        btnEndScroll = findViewById(R.id.btnEndScroll);
        btnEndScroll.setOnClickListener(this);

        imgUndo = findViewById(R.id.imgUndo);
        imgUndo.setOnClickListener(this);

        imgRedo = findViewById(R.id.imgRedo);
        imgRedo.setOnClickListener(this);

        imgSave = findViewById(R.id.imgSave);
        imgSave.setOnClickListener(this);

        imgClose = findViewById(R.id.imgClose);
        imgClose.setOnClickListener(this);

//        pixelEditorView.getSource().setImageResource(R.drawable.image);

        findViewById(R.id.rootView).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float touchX = event.getX();
                float touchY = event.getY();
                Log.e(TAG, "touchX="+touchX+" touchY="+touchY);
                return false;
            }
        });
    }

    @Override
    public void onEditTextChangeListener(final View rootView, String text, int colorCode) {
        TextEditorDialogFragment textEditorDialogFragment =
                TextEditorDialogFragment.show(this, text, colorCode);
        textEditorDialogFragment.setOnTextEditorListener((inputText, newColorCode) -> {
            final TextStyleBuilder styleBuilder = new TextStyleBuilder();
            styleBuilder.withTextColor(newColorCode);
            editor.editText(rootView, inputText, styleBuilder);
            mTxtCurrentTool.setText(R.string.label_text);
        });
    }

    @Override
    public void onAddViewListener(ViewType viewType, int numberOfAddedViews) {
        Log.d(TAG, "onAddViewListener() called with: viewType = [" + viewType + "], numberOfAddedViews = [" + numberOfAddedViews + "]");
    }

    @Override
    public void onRemoveViewListener(ViewType viewType, int numberOfAddedViews) {
        Log.d(TAG, "onRemoveViewListener() called with: viewType = [" + viewType + "], numberOfAddedViews = [" + numberOfAddedViews + "]");
    }

    @Override
    public void onStartViewChangeListener(ViewType viewType) {
        Log.d(TAG, "onStartViewChangeListener() called with: viewType = [" + viewType + "]");
        zoomLayout.setEnabled(false);
    }

    @Override
    public void onStopViewChangeListener(ViewType viewType) {
        Log.d(TAG, "onStopViewChangeListener() called with: viewType = [" + viewType + "]");
    }

    @Override
    public void onTouchSourceImage(MotionEvent event) {
        Log.d(TAG, "onTouchView() called with: event = [" + event + "]");
        zoomLayout.setEnabled(true);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnStartScroll:
                zoomLayout.setEnabled(true);
                break;
            case R.id.btnEndScroll:
                zoomLayout.setEnabled(false);
                break;

            case R.id.imgUndo:
                editor.undo();
                break;

            case R.id.imgRedo:
//                mEditor.redo();
                editor.clearAllViews();
                break;

            case R.id.imgSave:
                pixelEditorView.setStaticRect(null, 0);
                saveImage();
                break;

            case R.id.imgClose:
                onBackPressed();
                break;
        }
    }

    private void saveImage() {

        final String fileName = "image_tail_"+System.currentTimeMillis();
        boolean hasStoragePermission =
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PERMISSION_GRANTED;
        if (hasStoragePermission || isSdkHigherThan28()) {
            showLoading("Saving...");
            mSaveFileHelper.createCacheFile(fileName, (fileCreated, filePath, error, Uri) -> {
                if (fileCreated) {

                    SaveSettings saveSettings = new SaveSettings.Builder()
                            .setClearViewsEnabled(false)
                            .setTransparencyEnabled(false)
                            .build();
                    editor.saveAsIsd(filePath, saveSettings, new Editor.OnSaveListener() {
                        @Override
                        public void onSuccess(@NonNull Editor.ImageResult result) {
                            hideLoading();
//                            Log.d(TAG, "onSuccess ImageResult:"+result.toString());
                        }

                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            hideLoading();
                            showSnackbar("Failed to save Image");
                        }
                    });

                } else {
                    hideLoading();
                    showSnackbar(error);
                }
            });
        } else {
            requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onColorChanged(int colorCode) {
        editor.setShape(mShapeBuilder.withShapeColor(colorCode));
        mTxtCurrentTool.setText(R.string.label_brush);
    }

    @Override
    public void onOpacityChanged(int opacity) {
        editor.setShape(mShapeBuilder.withShapeOpacity(opacity));
        mTxtCurrentTool.setText(R.string.label_brush);
    }

    @Override
    public void onShapeSizeChanged(int shapeSize) {
        editor.setShape(mShapeBuilder.withShapeSize(shapeSize));
        mTxtCurrentTool.setText(R.string.label_brush);
    }

    @Override
    public void onShapePicked(ShapeType shapeType) {
        editor.setShape(mShapeBuilder.withShapeType(shapeType));
    }

    @Override
    public void onEmojiClick(String emojiUnicode) {
        editor.addEmoji(emojiUnicode);
        mTxtCurrentTool.setText(R.string.label_emoji);
    }

    @Override
    public void onStickerClick(Bitmap bitmap) {
        editor.addImage(bitmap);
        mTxtCurrentTool.setText(R.string.label_sticker);
    }

    @Override
    public void isPermissionGranted(boolean isGranted, String permission) {
        if (isGranted) {
            saveImage();
        }
    }

    private void showSaveDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.msg_save_image));
        builder.setPositiveButton("Save", (dialog, which) -> saveImage());
        builder.setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());
        builder.setNeutralButton("Discard", (dialog, which) -> finish());
        builder.create().show();

    }

    @Override
    public void onToolSelected(ToolType toolType) {
        switch (toolType) {
            case SHAPE:
                editor.setBrushDrawingMode(true);
                mShapeBuilder = new ShapeBuilder();
                editor.setShape(mShapeBuilder);
                mTxtCurrentTool.setText(R.string.label_shape);
                showBottomSheetDialogFragment(mShapeBSFragment);
                break;
            case TEXT:
                TextEditorDialogFragment textEditorDialogFragment = TextEditorDialogFragment.show(this);
                textEditorDialogFragment.setOnTextEditorListener((inputText, colorCode) -> {
                    final TextStyleBuilder styleBuilder = new TextStyleBuilder();
                    styleBuilder.withTextColor(colorCode);
//                    styleBuilder.withTextSize(30);
                    editor.addText(inputText, styleBuilder);
                    mTxtCurrentTool.setText(R.string.label_text);
                });
                break;
            case ERASER:
                editor.brushEraser();
                mTxtCurrentTool.setText(R.string.label_eraser_mode);
                break;
            case EMOJI:
                showBottomSheetDialogFragment(mEmojiBSFragment);
                break;
            case STICKER:
                showBottomSheetDialogFragment(mStickerBSFragment);
                break;
        }
    }

    private void showBottomSheetDialogFragment(BottomSheetDialogFragment fragment) {
        if (fragment == null || fragment.isAdded()) {
            return;
        }
        fragment.show(getSupportFragmentManager(), fragment.getTag());
    }

    @Override
    public void onBackPressed() {
        if (!editor.isCacheEmpty()) {
            showSaveDialog();
        } else {
            super.onBackPressed();
        }
    }

}
